#!/usr/bin/env python3
"""
实时监控前端测试活动
"""
import time
import subprocess
import re
from datetime import datetime

def monitor_frontend_activity():
    """实时监控前端活动"""
    print("🔍 开始监控前端测试活动...")
    print("=" * 60)
    
    last_web_count = 0
    last_budget_count = 0
    last_weather_count = 0
    
    while True:
        try:
            current_time = datetime.now().strftime("%H:%M:%S")
            
            # 检查web后端访问
            web_result = subprocess.run(
                ["grep", "-c", "GET /api/agents/status", "web_backend.log"],
                capture_output=True, text=True, cwd="/home/pony/codes/my/my_a2a"
            )
            web_count = int(web_result.stdout.strip()) if web_result.stdout.strip().isdigit() else 0
            
            # 检查BudgetAgent访问
            budget_result = subprocess.run(
                ["grep", "-c", "GET / HTTP/1.1", "budget_agent.log"],
                capture_output=True, text=True, cwd="/home/pony/codes/my/my_a2a"
            )
            budget_count = int(budget_result.stdout.strip()) if budget_result.stdout.strip().isdigit() else 0
            
            # 检查WeatherAgent访问
            weather_result = subprocess.run(
                ["grep", "-c", "GET / HTTP/1.1", "weather_agent.log"],
                capture_output=True, text=True, cwd="/home/pony/codes/my/my_a2a"
            )
            weather_count = int(weather_result.stdout.strip()) if weather_result.stdout.strip().isdigit() else 0
            
            # 检测新活动
            web_new = web_count - last_web_count
            budget_new = budget_count - last_budget_count
            weather_new = weather_count - last_weather_count
            
            if web_new > 0 or budget_new > 0 or weather_new > 0:
                print(f"[{current_time}] 检测到前端活动:")
                if web_new > 0:
                    print(f"  🌐 Web API: +{web_new} 次状态查询")
                if budget_new > 0:
                    print(f"  💰 BudgetAgent: +{budget_new} 次访问")
                if weather_new > 0:
                    print(f"  🌤️  WeatherAgent: +{weather_new} 次访问")
                print(f"  📊 累计: Web({web_count}) Budget({budget_count}) Weather({weather_count})")
                print("-" * 60)
            
            # 更新计数
            last_web_count = web_count
            last_budget_count = budget_count
            last_weather_count = weather_count
            
            time.sleep(2)  # 每2秒检查一次
            
        except KeyboardInterrupt:
            print("\n🛑 监控停止")
            break
        except Exception as e:
            print(f"⚠️  监控错误: {e}")
            time.sleep(5)

if __name__ == "__main__":
    monitor_frontend_activity()